/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.watchmen.mini.modules.sys.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.watchmen.mini.common.utils.ErrorMsg;
import com.watchmen.mini.common.utils.Result;
import com.watchmen.mini.modules.sys.entity.User;
import com.watchmen.mini.modules.sys.utils.UserUtils;
import com.watchmen.mini.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 手机端视图拦截器
 * @author ThinkGem
 * @version 2014-9-1
 */
public class MobileInterceptor extends BaseService implements HandlerInterceptor {

	@Autowired
	private TokenManager tokenManager;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
							 Object handler) throws Exception {
		if(handler instanceof HandlerMethod){
			String authorization = request.getHeader(Constants.AUTHORIZATION);
			if(authorization == null){
				authorization = request.getParameter(Constants.AUTHORIZATION);
			}
			//验证 token
			if(tokenManager.checkToken(authorization)){ //验证成功，则可以获取redis中的数据
				TokenModel model = tokenManager.getToken(authorization);
				if(model != null &&  model.getExpire() != null && model.getExpire()){
					returnJson(response, new Result(ErrorMsg.AUTH_FAIL.getCode(),"系统检测到您的账号已在其它终端登录，当前登录已经被迫下线。"));
					return false;
				}
				User user =  UserUtils.getByLoginName(model.getLoginName());
				if(user == null){
					returnJson(response, new Result(ErrorMsg.AUTH_ERROR));
					return false;
				}
				UserUtils.setUser(user);
				return true;
			}else{
				returnJson(response, new Result(ErrorMsg.AUTH_FAIL));
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
								Object handler, Exception ex) throws Exception {
	}

	private void returnJson(HttpServletResponse response, Result result) throws Exception{
		PrintWriter writer = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		try {
			String jsonString = JSON.toJSONString(result);
			writer = response.getWriter();
			writer.write(jsonString);//写回
			writer.flush();
		} catch (IOException e) {
			logger.error("response error",e);
		} finally {
			if (writer != null)
				writer.close();
		}
	}
}
